import uuid
from paddy_doctor.model.database import mongo

class User:

    def __init__(self, id, username, password, location):
        self.id = id
        self.username = username
        self.password = password
        self.location = location
        self.is_authenticated = False
        self.is_active = True
        self.is_anonymous = False
    
    def get_id(self):
        return self.id

    def to_json(self):
        if hasattr(self, 'token'):
            return {'id': self.id, 'username': self.username, 'location': self.location, 'token': self.token}
        else:
            return {'id': self.id, 'username': self.username, 'token': self.token}


    @staticmethod
    def login(username, password):
        document = mongo.db.user.find_one({'username': username})
        if document == None:
            return User.register(username, password)
        if document['password'] != password:
            return None
        user = User(document['id'], document['username'], document['password'], document['location'])
        # 文档见https://docs.python.org/3/library/uuid.html
        user.token = str(uuid.uuid4())
        User.users[user.token] = user
        return user

    @staticmethod
    def register(username, password):
        if not User.validateUsername(username):
            return None
        if not User.validatePassword(password):
            return None
        # 查找重复
        document = mongo.db.user.find_one({
            'username': username
        })
        if document != None:
            return None
        # 插入用户
        user_id = str(uuid.uuid4())
        document = mongo.db.user.insert_one(
            {'id': user_id, 'username': username, 'password': password, 'location': 'unknown'})
        if document == None:
            return None
        user = User(user_id, username, password, 'unknown')
        user.token = str(uuid.uuid4())
        User.users[user.token] = user
        return user

    @staticmethod
    def logout(user):
        del User.users[user.token]

    @staticmethod
    def find(token):
        user = User.users.get(token, None)
        if user != None:
            user.is_authenticated = True
        return user

    @staticmethod
    def validateUsername(username: str):
        if len(username) < 1:
            return False
        return True

    @staticmethod
    def validatePassword(password: str):
        if len(password) <= 5:
            return False
        return True

User.users = {}
